package com.srwl.mytx.fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONArray;
import com.srwl.mytx.Constant;
import com.srwl.mytx.Helper;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.activity.TopicDetailsActivity;
import com.srwl.mytx.adapter.MapBottomTopicAdapter;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.domain.Topic;
import com.srwl.mytx.service.TopicService;
import com.srwl.mytx.widget.NodataFooter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.jzvd.Jzvd;
import cn.jzvd.JzvdStd;
import me.dkzwm.widget.srl.MaterialSmoothRefreshLayout;
import me.dkzwm.widget.srl.SmoothRefreshLayout;
import me.dkzwm.widget.srl.extra.footer.MaterialFooter;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


public class HottestTopicFragment extends BaseFragment implements MapBottomTopicAdapter.CallbackToOutside {

    private static final String TAG = HottestTopicFragment.class.getSimpleName();

    private RecyclerView rl_topicList;
    //  private HomePageTopicAdapter topicAdapter;
    private MapBottomTopicAdapter topicAdapter;
    private List<Topic> topicList = new ArrayList<>();
    private int page = 1;
    private int size = 10;
    private boolean hasNextPage;
    private MaterialSmoothRefreshLayout refreshLayout;
    protected InteractionListener listener;
    private View fistView;
    private View lastView;
    private int _lastItemPosition;
    private int _firstItemPosition = -1;


    public static HottestTopicFragment newInstance() {
        return new HottestTopicFragment();
    }

    @Nullable
    @Override
    public View onCreateView(final LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_hottest_topic, container, false);
        refreshLayout = view.findViewById(R.id.refresh_layout);
        rl_topicList = view.findViewById(R.id.rl_topic_list);
        initRefreshLayout();
        //   topicAdapter = new HomePageTopicAdapter(getContext(), topicList);
        topicAdapter = new MapBottomTopicAdapter(getContext(), topicList);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext(), RecyclerView.VERTICAL, false);
        rl_topicList.setLayoutManager(linearLayoutManager);
        rl_topicList.setAdapter(topicAdapter);
        rl_topicList.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                //获取第一个可见view的位置
                int firstItemPosition = linearLayoutManager.findFirstVisibleItemPosition();
                int lastItemPosition = linearLayoutManager.findLastVisibleItemPosition();
                //获取可见view的总数
                int visibleItemCount = linearLayoutManager.getChildCount();

                if (_firstItemPosition < firstItemPosition) {
                    checkAndPauseVideoView(fistView);
                    _firstItemPosition = firstItemPosition;
                    _lastItemPosition = lastItemPosition;
                    fistView = recyclerView.getChildAt(0);
                    lastView = recyclerView.getChildAt(visibleItemCount - 1);
                } else if (_lastItemPosition > lastItemPosition) {
                    checkAndPauseVideoView(lastView);
                    _firstItemPosition = firstItemPosition;
                    _lastItemPosition = lastItemPosition;
                    fistView = recyclerView.getChildAt(0);
                    lastView = recyclerView.getChildAt(visibleItemCount - 1);
                }


            }
        });
        topicAdapter.setCallbackToOutside(this);
        loadHottestTopicData(false, true);
        return view;
    }

    private void checkAndPauseVideoView(View view) {
        if (view == null) {
            return;
        }
        Jzvd jzvd = view.findViewById(R.id.video_player);
        if (jzvd != null) {
            if (jzvd.state == Jzvd.STATE_PLAYING) {
                jzvd.resetProgressAndTime();
                JzvdStd.resetAllVideos();
            }
        }
    }


    public void setListener(InteractionListener listener) {
        this.listener = listener;
    }

    private void loadHottestTopicData(boolean isRefresh, boolean isFirst) {
        if (!Helper.getInstance().isNetworkConnected()) {
            if (isFirst) {
                topicAdapter.showErrorView();
                showToast_v1(getString(R.string.network_anomalies));
            } else {
                refreshLayout.refreshComplete();
                showToast_v1(getString(R.string.network_anomalies));
            }
            return;
        }
        if (isFirst && listener != null) {
            refreshLayout.setDisableRefresh(true);
            listener.showProgressBar(true);
        }
        Map<String, Object> body = new HashMap<>();
        body.put("page", page);
        body.put("size", size);
        RetrofitManager.getInstance().createRequest(TopicService.class)
                .queryHottestTopic(body)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        if (isFirst && listener != null) {
                            refreshLayout.setDisableRefresh(false);
                            listener.showProgressBar(false);

                        } else {
                            refreshLayout.refreshComplete();
                        }
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            topicAdapter.showErrorView();
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, result.getMsg());
                            topicAdapter.showErrorView();
                            return;
                        }

                        Object data = result.getData();
                        if (data == null) {
                            if (isFirst) {
                                topicAdapter.showNoDataView();
                                return;
                            }
                            changeFooter();
                            hasNextPage = false;
                            return;
                        }
                        JSONArray jsonArray = (JSONArray) data;
                        Log.d(TAG, "onResponse: " + jsonArray.toJSONString());
                        List<Topic> topics = null;
                        try {
                            topics = jsonArray.toJavaList(Topic.class);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        if (topics == null || topics.size() == 0 && refreshLayout != null) {
                            hasNextPage = false;
                            changeFooter();
                            return;
                        }
                        if (topics.size() < size && refreshLayout != null) {
                            hasNextPage = false;
                            changeFooter();
                        } else {
                            hasNextPage = true;
                        }
                        if (isRefresh) {
                            topicList.clear();
                        }
                        topicList.addAll(topics);
                        if (topicList.size() != 0) {
                            topicAdapter.showNormalView(page * size - size, size);
                            page++;
                        } else {
                            //当topicList中没有数据时，显示为没有数据的item
                            topicAdapter.showNoDataView();
                        }
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {

                        if (isFirst && listener != null) {
                            refreshLayout.setDisableRefresh(false);
                            listener.showProgressBar(false);

                        } else {
                            refreshLayout.refreshComplete();
                        }
                        Log.e(TAG, t.getMessage());
                        topicAdapter.showErrorView();
                    }
                });

    }

    private void changeFooter() {

        refreshLayout.postDelayed(() -> {
            if (getActivity() != null) {
                refreshLayout.setFooterView(new NodataFooter(getActivity()));
            }
        }, 1000);
    }

    void initRefreshLayout() {
        refreshLayout.setEnableOverScroll(false);
        refreshLayout.setDisableRefresh(false);
        refreshLayout.setDisableLoadMore(false);

        refreshLayout.setOnRefreshListener(new SmoothRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefreshing() {
                page = 1;
                refreshLayout.setFooterView(new MaterialFooter(getActivity()));
                loadHottestTopicData(true, false);

                // nearbySearch(true, false);


            }

            @Override
            public void onLoadingMore() {
                if (hasNextPage) {
                    loadHottestTopicData(false, false);
                    // nearbySearch(false, false);

                } else {
                    refreshLayout.refreshComplete();
                }
            }

        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != Activity.RESULT_OK || data == null) {
            return;
        }
        Topic updateTopic = data.getParcelableExtra(Constant.EXTRA_INFO_TOPIC);
        if (updateTopic == null) {
            return;
        }
        for (int i = 0; i < topicList.size(); i++) {
            Topic topic = topicList.get(i);
            if (TextUtils.equals(updateTopic.getId(), topic.getId())) {
                //主题被删除或者下架处理
                if (data.getBooleanExtra(Constant.EXTRA_TOPIC_DELETE, false) || data.getBooleanExtra(Constant.EXTRA_TOPIC_BACK_OUT, false)) {
                    topicList.remove(i);
                    topicAdapter.notifyItemRemoved(i);
                    topicAdapter.notifyItemRangeChanged(i, topicList.size() - i);
                } else if (data.getBooleanExtra(Constant.EXTRA_TOPIC_CHANGE, false)) {//主题改变，这个对应的可能很多，比如评论数量增加
                    topicList.remove(i);
                    topicList.add(i, updateTopic);
                    topicAdapter.notifyItemChanged(i);
                }
                break;
            }
        }
    }

    @Override
    public void jumpPage(Topic topic) {
        startActivityForResult(new Intent(getContext(), TopicDetailsActivity.class).putExtra(Constant.EXTRA_INFO_TOPIC, topic), GaoDeMapFragment.REQUEST_CODE_TO_TOPIC_DETAIL);
    }

    @Override
    public void commentJumpPage(Topic topic) {
        startActivityForResult(new Intent(getContext(), TopicDetailsActivity.class).putExtra(Constant.EXTRA_INFO_TOPIC, topic)
                .putExtra(Constant.EXTRA_INFO_MESSAGE, "comment"), GaoDeMapFragment.REQUEST_CODE_TO_TOPIC_DETAIL);
    }

    public interface InteractionListener {

        void showProgressBar(boolean isShowProgressBar);
    }


}

